package com.yang.sqlSession;

import com.yang.pojo.Configuration;
import org.junit.runners.Parameterized;

import java.lang.reflect.*;
import java.time.OffsetDateTime;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {

        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> list = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空,或者查询结果过多!");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理来为Mapper接口生成代理对象并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(
                    //当前对象的应用
                    Object proxy,
                    //当前被调用方法的引用
                    Method method,
                    //传递的参数
                    Object[] args) throws Throwable {
                //底层还是去执行JDBC代码.
                //根据不同情况去调用selectOne,或者selectList
                //准备参数statmentid,
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statmentId = className + "." + methodName;
                //准备参数params:args

                //获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                //判断是否进行了泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> objects = selectList(statmentId, args);
                    return objects;
                }
                return selectOne(statmentId, args);

            }
        });

        return (T) proxyInstance;
    }
}
